package net.hnedu.action;

import java.util.Collection;
import java.util.Iterator;

import org.apache.struts.validator.*;
import org.apache.struts.action.*;
import javax.servlet.http.*;
import net.hnedu.search.resource.*;
import com.hnedu.util.StringUtils;
import net.hnedu.map.ResResource;

public class ResSearchAction
    extends MyDispatchAction {
  public ActionForward execute(ActionMapping actionMapping,
                               ActionForm actionForm,
                               HttpServletRequest request,
                               HttpServletResponse response) throws Exception {
    /**@todo: complete the business logic here, this is just a skeleton.*/
    //DynaValidatorForm form = (DynaValidatorForm) actionForm;

    String key = request.getParameter("serachKey");
    String creator = request.getParameter("searchCreator");
    int offset = 0;
    int rows = 20;
    String offsetStr = request.getParameter("offset");
    if(StringUtils.isNumeric(offsetStr)) {
      offset = Integer.parseInt(offsetStr);
    }
    offset = (offset / rows) * rows;

    ResourceSearchQuery query = new ResourceSearchQuery();


    if(key.length() > 0) {
      query.setSearchString(key);
    }
    if(creator.length() > 0) {
      query.setCreator(creator);
    }

    query.searchDocuments(offset,rows);
    int hitCount = query.getHitCount();


    Collection result = query.getPostResult();
    System.out.println("----------------------------------start");
    for(Iterator iter = result.iterator();iter.hasNext();) {
      ResResource res = (ResResource)iter.next();
      System.out.println(res.getResTitle());
    }
    System.out.println("----------------------------------end");

    request.setAttribute("serachKey",key);
    request.setAttribute("searchCreator",creator);
    request.setAttribute("offset",new Integer(offset));
    request.setAttribute("rows",new Integer(rows));
    request.setAttribute("TotalRes",new Integer(hitCount));
    request.setAttribute("ResResources",result);

    return actionMapping.findForward("searchResult");
  }
}
